package com.school.dao.impl;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.school.dao.CourseSelectDao;
import com.school.domain.Course;
import com.school.domain.CourseSelection;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;

public class CourseSelectDaoImpl implements CourseSelectDao {
    private DataSource dataSource = new ComboPooledDataSource();
    private QueryRunner queryRunner = new QueryRunner(dataSource);
    private final CourseDaoImpl courseDao = new CourseDaoImpl();

    @Override
    public boolean add(CourseSelection courseSelection) {
        int result = 0;
        Course course = courseDao.findById(courseSelection.getCoid());
//        没有这门课或人数已满
        if (course == null || course.getNowNum() == course.getNum()) return false;
        try {
            result = queryRunner.update("insert into courseSelection values(?, ?, ?)", null, courseSelection.getSid(), courseSelection.getCoid());
        } catch (SQLException throwables) {
            return false;
        }
        // 课程的已选课程人数加一
        course.setNowNum(course.getNowNum()+1);
        return result == 1 && courseDao.update(course);
    }

    @Override
    public List<CourseSelection> findBySid(long sid) {
        List<CourseSelection> execute = null;
        try {
            execute = queryRunner.query("select * from courseSelection where sid = " + sid, new BeanListHandler<CourseSelection>(CourseSelection.class));
        } catch (SQLException throwables) {
            return null;
        }
        return execute;
    }

    @Override
    public List<CourseSelection> findByCoid(long coid) {
        List<CourseSelection> execute = null;
        try {
            execute = queryRunner.query("select * from courseSelection where coid = " + coid, new BeanListHandler<CourseSelection>(CourseSelection.class));
        } catch (SQLException throwables) {
            return null;
        }
        return execute;
    }

    @Override
    public List<CourseSelection> findAll() {
        List<CourseSelection> execute = null;
        try {
            execute = queryRunner.query("select * from courseSelection", new BeanListHandler<CourseSelection>(CourseSelection.class));
        } catch (SQLException throwables) {
            return null;
        }
        return execute;
    }
}
